﻿//-----------------------------------------------------------------------
// <copyright file="BookListPage.xaml.cs" company="FIT VUT">
//     Copyright (c) FIT VUT. All rights are reserved.
// </copyright>
//----------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using BookCaching.CustomControls;
using BookCaching.Data;
using BookCaching.Misc;
using BookCaching.Settings;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace BookCaching.Pages
{
    public partial class BookListPage : PhoneApplicationPage
    {
        public BookListPage()
        {
            this.InitializeComponent();

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("AddBookButtonLabel");
            (ApplicationBar.Buttons[1] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("SettingsButtonLabel");
        }

        private IEnumerable returnBookSource(List<Knihotoc_WCFService.Book> lb)
        {
            List<Book> booksSource = new List<Book>();

            foreach (Knihotoc_WCFService.Book book in lb)
            {
                booksSource.Add(new Book(book));
            }

            for (int i = 0; i < booksSource.Count; ++i)
            {
                booksSource[i].ImageThumbnailVisibility = CurrentSettings.Instance.BookListThumbnailsVisibility;
            }

            booksSource.Sort((x, y) => string.Compare(x.Title, y.Title));

            IEnumerable booksByTitle;

            switch (CurrentSettings.Instance.BookListOrderingOrder)
            {
                case OrderingOrder.ascending:
                    booksByTitle = from book in booksSource
                                   group book by book.TitleFirstLetter into c
                                   orderby c.Key ascending
                                   select new Group<Book>(c.Key, c);
                    break;

                case OrderingOrder.descending:
                    booksByTitle = from book in booksSource
                                   group book by book.TitleFirstLetter into c
                                   orderby c.Key descending
                                   select new Group<Book>(c.Key, c);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("This value of the enum is not valid!");
            }

            return booksByTitle;
        }

        private void Client_GetBooksOwnedByUserCompleted(object sender, Knihotoc_WCFService.GetBooksOwnedByUserCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }

            addedBooksLongListSelector.ItemsSource = returnBookSource(e.Result.ToList());
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);

                Knihotoc_WCFService.Knihotoc_WP7ServiceClient client = new Knihotoc_WCFService.Knihotoc_WP7ServiceClient();
                
                client.GetBooksOwnedByUserCompleted += Client_GetBooksOwnedByUserCompleted;
                client.GetBooksOwnedByUserAsync(CurrentSettings.Instance.User.ID);

                client.GetBooksFoundByUserCompleted += client_GetBooksFoundByUserCompleted;
                client.GetBooksFoundByUserAsync(CurrentSettings.Instance.User.ID);
            }
            catch
            {   // TODO, log
                return;
            }

            ApplicationBar.BackgroundColor = CurrentSettings.Instance.ForegroundColor.Color;
        }

        void client_GetBooksFoundByUserCompleted(object sender, Knihotoc_WCFService.GetBooksFoundByUserCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }

            foundBooksLongListSelector.ItemsSource = returnBookSource(e.Result.ToList());
        }

        #region User input 
        private void BookItemTemplate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int bookID = ((GridID)sender).ID;

            NavigationService.Navigate(new Uri("/Pages/BookDetailPage.xaml?BookID=" + bookID.ToString(), UriKind.Relative));
        }

        private void FindBookButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookFindPage.xaml", UriKind.Relative));
        }

        private void SettingsApplicationBarButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BooklistSettingsPage.xaml", UriKind.Relative));
        }
        #endregion        
    }
}